######################################
# Shp图形最大外接矩形裁剪
######################################

import os
import sys

from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import QSettings, Qt, pyqtSignal
from PyQt5.QtGui import QPalette, QBrush, QPixmap, QIcon
from PyQt5.QtWidgets import *

from CropRasterByShp import CropRasterByShp


class WindowCropByShp(QtWidgets.QDialog):
    # 窗口关闭信号槽
    closeEvtSig = pyqtSignal()

    def __init__(self, parent=None):
        QtWidgets.QDialog.__init__(self, parent)
        self.cropRasterByShpThread = None
        self.setObjectName("WindowCropByShp")
        self.resize(641, 361)
        self.setWindowTitle("根据Shp图形裁剪")
        self.setWindowIcon(QIcon("./images/setup.png"))
        window_pale = QPalette()
        window_pale.setBrush(self.backgroundRole(), QBrush(QPixmap("./images/bg.png")))
        self.setPalette(window_pale)
        # Qt.WindowMaximizeButtonHint |
        self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowMinimizeButtonHint | Qt.WindowCloseButtonHint)

        self.label_2 = QtWidgets.QLabel(parent=self)
        self.label_2.setGeometry(QtCore.QRect(40, 100, 100, 20))
        self.label_2.setObjectName("label_2")
        self.label_2.setStyleSheet("color:white")
        self.label_2.setText("影像文件：")

        self.label_3 = QtWidgets.QLabel(parent=self)
        self.label_3.setGeometry(QtCore.QRect(40, 150, 100, 20))
        self.label_3.setObjectName("label_3")
        self.label_3.setStyleSheet("color:white")
        self.label_3.setText("SHP文件：")

        self.label_4 = QtWidgets.QLabel(parent=self)
        self.label_4.setGeometry(QtCore.QRect(40, 200, 100, 20))
        self.label_4.setObjectName("label_4")
        self.label_4.setStyleSheet("color:white")
        self.label_4.setText("存储路径：")

        self.lineEdit_2 = QtWidgets.QLineEdit(parent=self)
        self.lineEdit_2.setGeometry(QtCore.QRect(150, 100, 370, 21))
        self.lineEdit_2.setObjectName("lineEdit_2")

        self.lineEdit_3 = QtWidgets.QLineEdit(parent=self)
        self.lineEdit_3.setGeometry(QtCore.QRect(150, 150, 370, 21))
        self.lineEdit_3.setObjectName("lineEdit_3")

        self.lineEdit_4 = QtWidgets.QLineEdit(parent=self)
        self.lineEdit_4.setGeometry(QtCore.QRect(150, 200, 370, 21))
        self.lineEdit_4.setObjectName("lineEdit_4")

        self.pushButton_3 = QtWidgets.QPushButton(parent=self)
        self.pushButton_3.setGeometry(QtCore.QRect(540, 100, 50, 21))
        self.pushButton_3.setObjectName("pushButton_3")
        self.pushButton_3.setText("选择")
        self.pushButton_3.clicked.connect(self.selectRasterFile)

        self.pushButton_4 = QtWidgets.QPushButton(parent=self)
        self.pushButton_4.setGeometry(QtCore.QRect(540, 150, 50, 21))
        self.pushButton_4.setObjectName("pushButton_4")
        self.pushButton_4.clicked.connect(self.selectShpFile)
        self.pushButton_4.setText("选择")

        self.pushButton_5 = QtWidgets.QPushButton(parent=self)
        self.pushButton_5.setGeometry(QtCore.QRect(540, 200, 50, 21))
        self.pushButton_5.setObjectName("pushButton_5")
        self.pushButton_5.clicked.connect(self.selectOutputDir)
        self.pushButton_5.setText("选择")

        self.pushButton_cal = QtWidgets.QPushButton(parent=self)
        self.pushButton_cal.setGeometry(QtCore.QRect(200, 270, 100, 30))
        self.pushButton_cal.setObjectName("pushButton_cal")
        self.pushButton_cal.clicked.connect(self.crop_do)
        self.pushButton_cal.setText("裁剪")

        self.pushButton_back = QtWidgets.QPushButton(parent=self)
        self.pushButton_back.setGeometry(QtCore.QRect(350, 270, 100, 30))
        self.pushButton_back.setObjectName("pushButton_back")
        self.pushButton_back.clicked.connect(self.close)
        self.pushButton_back.setText("返回")

        # 创建QSettings，配置文件是tmp/.temp
        self.setting = QSettings('tmp/.temp', QSettings.IniFormat)
        # 设置UTF8编码，反正保存配置文件时出现乱码
        self.setting.setIniCodec('UTF-8')

        # 读取上一次的目录路径
        self.last_path = self.setting.value('LastFilePath')

        # 如果字符串为空，将路径索引到根目录
        if self.last_path is None:
            self.last_path = '/'  # 根盘符
        self.file_path_list = ""

    def closeEvent(self, event) -> None:
        self.closeEvtSig.emit()

    def selectRasterFile(self):
        filename, _ = QFileDialog.getOpenFileName(self, "选择影像文件", self.last_path, "TIFF影像(*.tif)")
        # 如果文件为空，取消后续指令
        if filename is None or len(filename) <= 0:
            return
        try:
            # 将多个文件转为列表
            self.file_path_list = [fname_item for fname_item in filename]

            # 保存当前目录的路径到配置文件中，另外如果不存在'tmp/.temp'文件该函数会自动创建
            self.setting.setValue('LastFilePath', os.path.dirname(self.file_path_list[0]))

            # 将路径设为''程序会使用上一次的路径
            self.last_path = ''

        except Exception as e:
            # 发生异常，弹窗警告
            msg = QtWidgets.QMessageBox.warning(self, "Warning", "选择影像文件%s" % e, buttons=QtWidgets.QMessageBox.Ok,
                                                defaultButton=QtWidgets.QMessageBox.Ok)
        self.lineEdit_2.setText(filename)

    def selectShpFile(self):
        filename, _ = QFileDialog.getOpenFileName(self, "选择SHP文件", self.last_path, "Shapefile(*.shp)")
        # 如果文件为空，取消后续指令
        if filename is None or len(filename) <= 0:
            return
        try:
            # 将多个文件转为列表
            self.file_path_list = [fname_item for fname_item in filename]

            # 保存当前目录的路径到配置文件中，另外如果不存在'tmp/.temp'文件该函数会自动创建
            self.setting.setValue('LastFilePath', os.path.dirname(self.file_path_list[0]))

            # 将路径设为''程序会使用上一次的路径
            self.last_path = ''

        except Exception as e:
            # 发生异常，弹窗警告
            msg = QtWidgets.QMessageBox.warning(self, "Warning", "选择SHP文件%s" % e, buttons=QtWidgets.QMessageBox.Ok,
                                                defaultButton=QtWidgets.QMessageBox.Ok)
        self.lineEdit_3.setText(filename)

    def selectOutputDir(self):
        dir = QFileDialog.getExistingDirectory(self, "选择存储路径", self.last_path)
        # 如果文件为空，取消后续指令
        if dir is None or len(dir) <= 0:
            return
        try:
            # 将多个文件转为列表
            self.file_path_list = [fname_item for fname_item in dir]

            # 保存当前目录的路径到配置文件中，另外如果不存在'tmp/.temp'文件该函数会自动创建
            self.setting.setValue('LastFilePath', os.path.dirname(self.file_path_list[0]))

            # 将路径设为''程序会使用上一次的路径
            self.last_path = ''

        except Exception as e:
            # 发生异常，弹窗警告
            msg = QtWidgets.QMessageBox.warning(self, "Warning", "选择存储路径%s" % e, buttons=QtWidgets.QMessageBox.Ok,
                                                defaultButton=QtWidgets.QMessageBox.Ok)

        self.lineEdit_4.setText(dir + "/")

    def crop_do(self):

        if self.lineEdit_2.text() == "":
            QMessageBox.warning(self, "警告", "影像文件不能为空！", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            return
        if self.lineEdit_3.text() == "":
            QMessageBox.warning(self, "警告", "shp文件不能为空！", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            return
        if self.lineEdit_4.text() == "":
            QMessageBox.warning(self, "警告", "存储路径不能为空！", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            return
        raster_file = self.lineEdit_2.text()
        shp_file = self.lineEdit_3.text()
        out_dir = self.lineEdit_4.text()
        self.pushButton_cal.setEnabled(False)
        self.cropRasterByShpThread = CropRasterByShp(raster_file, shp_file, out_dir)
        self.cropRasterByShpThread.finishedSig.connect(self.info)
        self.cropRasterByShpThread.errorSig.connect(self.warm)
        self.cropRasterByShpThread.start()
        # super().accept()

    def warm(self, msg):
        self.pushButton_cal.setEnabled(True)
        QMessageBox.warning(self, "报错", msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)

    def info(self, msg):
        self.pushButton_cal.setEnabled(True)
        QMessageBox.information(self, "提示", msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    mainWindow = WindowCropByShp()
    mainWindow.show()
    sys.exit(app.exec_())
